package com.zbdx.controller;

import com.zbdx.util.DruidUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

@WebServlet("/shopping/updateUserInfo")
public class UpdateServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取表单中的数据
        String username = req.getParameter("username");
        String email = req.getParameter("email");
        String phone = req.getParameter("phone");
        String address = req.getParameter("address");

        // 数据库连接和SQL执行逻辑
        Connection conn = null;
        PreparedStatement pstmt = null;

        try {
            // 获取数据库连接
            conn = DruidUtil.getConnection();

            // 编写SQL语句，更新用户信息
            String sql = "UPDATE users2 SET email = ?, phone = ?, address = ? WHERE username = ?";
            pstmt = conn.prepareStatement(sql);

            // 设置SQL参数
            pstmt.setString(1, email);
            pstmt.setString(2, phone);
            pstmt.setString(3, address);
            pstmt.setString(4, username);

            // 执行更新操作
            int rowsAffected = pstmt.executeUpdate();
            if (rowsAffected > 0) {
                // 更新成功，返回成功页面
                resp.sendRedirect("shopping.jsp");
            } else {
                // 更新失败，返回错误信息
                req.setAttribute("error", "更新用户信息失败");
                req.getRequestDispatcher("editUserInfo.jsp").forward(req, resp);
            }
        } catch (SQLException e) {
            e.printStackTrace();
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "数据库连接错误");
        } finally {
            // 关闭数据库连接
            DruidUtil.close(conn);
        }
    }
}
